package com.houduan.controller;

import com.houduan.dao.UserDao;
import com.houduan.model.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class UserServlet extends HttpServlet {

    private UserDao userDao;

    @Override
    public void init() throws ServletException {
        super.init();
        userDao = new UserDao(); // 初始化 UserDao
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String action = request.getParameter("action");

        // 如果 action 参数为 null，并且用户直接访问 account_management.jsp，重定向到 UserServlet?action=list
        if (action == null) {
            response.sendRedirect("UserServlet?action=list");
            return;
        }

        switch (action) {
            case "edit":
                showEditForm(request, response);
                break;
            case "delete":
                deleteUser(request, response);
                break;
            case "search":
                searchUsers(request, response);
                break;
            case "list":
            default:
                listUsers(request, response);
                break;
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String action = request.getParameter("action");

        switch (action) {
            case "insert":
                insertUser(request, response);
                break;
            case "update":
                updateUser(request, response);
                break;
            default:
                listUsers(request, response);
        }
    }

    // 列出所有用户
    private void listUsers(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<User> userList = userDao.getAllUsers();
        request.setAttribute("users", userList);
        request.getRequestDispatcher("account_management.jsp").forward(request, response);
    }

    // 展示编辑表单
    private void showEditForm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        User existingUser = userDao.getUserById(id);
        request.setAttribute("user", existingUser);
        request.getRequestDispatcher("user_form.jsp?action=edit").forward(request, response);
    }

    // 删除用户
    private void deleteUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        userDao.deleteUser(id);
        response.sendRedirect("UserServlet?action=list");
    }

    // 查找用户
    private void searchUsers(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String query = request.getParameter("query"); // 获取查询参数（用户名或 ID）
        List<User> searchResult = userDao.searchUsers(query); // 调用 UserDao 中的查询方法
        request.setAttribute("users", searchResult); // 将查询结果设置到 request 属性中
        request.getRequestDispatcher("account_management.jsp").forward(request, response); // 转发到用户列表页面
    }

    // 插入新用户
    private void insertUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        String gender = request.getParameter("gender");
        double balance = Double.parseDouble(request.getParameter("balance"));

        User newUser = new User(username, password, email, phone, gender, balance);
        userDao.addUser(newUser);

        response.sendRedirect("UserServlet?action=list");
    }

    // 更新用户信息
    private void updateUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id")); // 用户 ID 必须存在，不会为空
        User existingUser = userDao.getUserById(id); // 获取现有用户数据

        // 获取表单中的值
        String username = request.getParameter("username");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        String gender = request.getParameter("gender");
        String balanceStr = request.getParameter("balance");

        // 如果字段为空，则保持原值
        if (username != null && !username.trim().isEmpty()) {
            existingUser.setUsername(username);
        }
        if (email != null && !email.trim().isEmpty()) {
            existingUser.setEmail(email);
        }
        if (phone != null && !phone.trim().isEmpty()) {
            existingUser.setPhone(phone);
        }
        if (gender != null && !gender.trim().isEmpty()) {
            existingUser.setGender(gender);
        }
        if (balanceStr != null && !balanceStr.trim().isEmpty()) {
            try {
                double balance = Double.parseDouble(balanceStr);
                existingUser.setBalance(balance);
            } catch (NumberFormatException e) {
                // 如果 balanceStr 无法解析为数字，保持原值
                System.err.println("Invalid balance input: " + balanceStr);
            }
        }

        // 更新用户信息
        userDao.updateUser(existingUser);

        // 重定向到用户列表
        response.sendRedirect("UserServlet?action=list");
    }
}
